/**
 *
 * Copyright (C) 2008  Igor Vdovichenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * Though a sincere effort has been made to deliver a professional,
 * quality product,the library itself is distributed WITHOUT ANY WARRANTY;
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 */
package com.vin.scriptutils.utils.unix;

import com.vin.scriptutils.UString;
import com.vin.scriptutils.utils.ScriptTextProvider;
import com.vin.scriptutils.utils.UnixCommandBuilder;
import com.vin.scriptutils.utils.ssh.ResultReader;
import com.vin.scriptutils.utils.ssh.SshCommand;
import com.vin.scriptutils.utils.ssh.SshTaskExec;
import com.vin.scriptutils.utils.ssh.exception.SshTaskExecException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;



/**
 *
 * @author igor
 */
public class BundledFilesUtils extends SshCommand {
    
    private ScriptTextProvider scriptTextProvider;

    /**
     *
     * @param sshTask
     * @param pathToScripts
     */
    public BundledFilesUtils(SshTaskExec sshTask, String pathToBundledFiles) {
        super(sshTask);
        setPath(pathToBundledFiles);
    }

    /**
     *
     * @param pathToBundledFiles
     * @return
     */
    public BundledFilesUtils setPath(final String pathToBundledFiles){
        this.scriptTextProvider = new ScriptTextProvider(pathToBundledFiles);
        return this;
    }

    /**
     *
     * @return ScriptTextProvider
     */
    public ScriptTextProvider getScriptTextProvider() {
        return this.scriptTextProvider;
    }
   

    /**
     * Executes local bundled script, on remote system, script stored in default user directory
     * @param scriptFileName local bundled script filename, i.e. "test.sh"
     * @param argv Script arguments
     * @return
     * @throws java.io.IOException
     * @throws com.vin.scriptutils.utils.ssh.exception.SshTaskExecException
     * @throws java.lang.InterruptedException
     */
    public ResultReader executeScript(String scriptFileName, String...argv) throws IOException, SshTaskExecException, InterruptedException {

        UnixCommandBuilder unixBuilder = new UnixCommandBuilder();
        String scpt = getScriptTextProvider().getScriptText(scriptFileName);

        if(scpt == null){
            throw new IllegalArgumentException( "Cannot find bundled file!" );
        }
        
        // get current directory
        unixBuilder.command("pwd");
        ResultReader rd = execute(unixBuilder);
        if (rd.isError()) {
            return null;
        }

        String root = rd.getFirstLineStdOutput();
        String scriptPath = UString.getUnixRightPathString(root, scriptFileName);

        return execute(scriptPath, scpt, argv);

    }

    /**
     * Executes local bundled script, on remote system
     * @param scriptFileName
     * @param remScriptPath path, where is remote script will be stored
     * @return
     * @throws java.io.IOException
     * @throws com.vin.scriptutils.utils.ssh.exception.SshTaskExecException
     * @throws java.lang.InterruptedException
     */
    public ResultReader executeScriptPath(String scriptFileName, String remScriptPath, String...argv) throws IOException, SshTaskExecException, InterruptedException {
        String script = getScriptTextProvider().getScriptText(scriptFileName);
        return execute(remScriptPath, script, argv);

    }

    /**
     *
     * @param remScriptPath
     * @param script
     * @param argv
     * @return
     * @throws java.io.IOException
     * @throws com.vin.scriptutils.utils.ssh.exception.SshTaskExecException
     * @throws java.lang.InterruptedException
     */
    protected ResultReader execute(String remScriptPath, String script, String...argv) throws IOException, SshTaskExecException, InterruptedException {

        UnixCommandBuilder unixBuilder = new UnixCommandBuilder();
        ResultReader rd;

        // create script file
        unixBuilder
                .command("cat")
                .redirectOut()
                .argvQ(remScriptPath)                
                ;        

        byte[] attachInfoBytes = script.getBytes("UTF-8");
        rd = execute(unixBuilder.toCommandLine(), new ByteArrayInputStream(attachInfoBytes));
        if(rd.isError()){
            return null;
        }

        // set execution params on script
        unixBuilder.reset();
        unixBuilder
                //.command("sudo")
                .command("chmod").argv("+x").argvQ(remScriptPath);

        rd = execute(unixBuilder);
        if (rd.isError()) {
            return null;
        }

        // execute remote script
        if(argv.length == 0){
            unixBuilder.command(remScriptPath);
        } else {
            unixBuilder.command(remScriptPath).argvQ(argv);
        }
        
        return execute(unixBuilder);
        
    }

    /**
     * 
     * @param fileName
     * @param remFilePath
     * @return
     * @throws java.io.IOException
     * @throws com.vin.scriptutils.utils.ssh.exception.SshTaskExecException
     * @throws java.lang.InterruptedException
     */
    public ResultReader putBinFile(String fileName, String remFilePath) throws IOException, SshTaskExecException, InterruptedException {

        InputStream scrStream = getScriptTextProvider().getScriptStream(fileName);
        if (scrStream == null) {
            throw new IllegalArgumentException( "Cannot find bundled file!" );
        }

        UnixShellUtils usu = new UnixShellUtils(getSshTaskExec());
        return usu.putBinFile(scrStream, remFilePath);
    }

}


